<template>
  <Layout>
    <Form ref="queryForm" :model="dataToQuery" :label-width="170">
      <Row v-show="!switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="二级集团：" prop="twoLevelOrgName">
            <Select v-model="dataToQuery.twoLevelOrgName" filterable>
              <Option v-for="item in twoLevelOrgs" :value="item.orgName" :key="item.orgId">{{ item.orgName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label='企业名称：'>
            <Select clearable filterable style="width:300px" v-model="dataToQuery.companyName" placeholder="请选择企业"
                    :remote-method="remoteMethodSelectOrg"
                    :default-label="defaultLabel"
                    :loading="orgLoading">
              <Option v-for="(option, index) in orgLists" :value="option.orgName" :key="index">{{ option.orgName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text">展开
              <Icon type="ios-arrow-down"/>
            </Button>
          </div>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="二级集团：" prop="twoLevelOrgName">
            <Select v-model="dataToQuery.twoLevelOrgName" filterable>
              <Option v-for="item in twoLevelOrgs" :value="item.orgName" :key="item.orgId">{{ item.orgName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label='企业名称：'>
            <Select clearable filterable style="width:300px" v-model="dataToQuery.companyName" placeholder="请选择企业"
                    :remote-method="remoteMethodSelectOrg"
                    :default-label="defaultLabel"
                    :loading="orgLoading">
              <Option v-for="(option, index) in orgLists" :value="option.orgName" :key="index">{{ option.orgName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label='分管企业或分子公司：'>
            <Input class='query-form-el' type='text' v-model='dataToQuery.subsidiaryCompany'></Input>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form2">
        <div style="float: right;">
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
          <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
          <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text">收起
            <Icon type="ios-arrow-up"/>
          </Button>
        </div>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <download-button :api="exportUrl" :queryForm="dataToQuery" />
          <!-- <Button type="primary" class="ivu-btn-add" icon="md-cloud-download" @click="exportList">导出</Button> -->
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
           :loading='pageStatus.loading' @on-expand="onExpand"
           border :columns="columns1" :data="dataTable">
    </Table>
    <!--分页-->
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
        <!-- <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange1" @on-page-size-change="pageSizeChange1" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator /> -->
      </Col>
    </Row>
    <!--新增、修改、详情-->
    <Modal :title="mode == 'view' ?'在职在岗职业病病例统计表详情':'在职在岗职业病病例统计表'" :transfer=false
           :mask-closable="false"
           v-model="dialogShow" v-if="dataToView && dialogShow" :width=850 class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'modal-form'"
                :show-message="false" :model="dataToView" :rules="mode === 'view'?{} :ruleCustom"
                :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?140:null">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='企业名称：' prop='companyId'>
                  <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                  <cascader-dom v-else ref='orgCascader' @setOrgInfo='setCompanyId' @setOrgname="setCompanyName"
                                :orgTree="true" :currentOrgId="dataToView.companyId"
                                :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}"></cascader-dom>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='分管企业或分子公司：' prop='subsidiaryCompany'>
                  <div v-if="mode === 'view'">{{ dataToView.subsidiaryCompany }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写分管企业或分子公司" type='text'
                         v-model='dataToView.subsidiaryCompany'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='在岗职业病人数：' prop='patientNumber'>
                  <div v-if="mode === 'view'">{{ dataToView.patientNumber }}</div>
                  <InputNumber v-else class='query-form-el' disabled placeholder="请填写在岗职业病人数" min="0"
                               type='text' v-model='dataToView.patientNumber'></InputNumber>
                </FormItem>
              </Col>
              <Col span="11"></Col>
            </Row>

            <Row>
              <Col span="23" class="query-form" style="margin-left: 15px">
                <Button v-if="mode !== 'view'" class="ivu-btn-add" icon="md-add"
                        @click="itemModel=true,itemAdd=true;detailItem={contactYears:0}">新增在岗职业病人信息
                </Button>
                <Table highlight-row stripe border style="margin-top:10px;margin-bottom: 10px" :max-height="350"
                       :columns="itemColumn"
                       :data="dataToView.items">
                </Table>
              </Col>

            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='填报人：' prop='createUserName'>
                  <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写填报人" type='text' readonly
                         v-model='dataToView.createUserName'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='填报时间：' prop='createDate'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                  <DatePicker v-else class="query-form-el" placeholder="请选择填报时间" readonly
                              v-model='dataToView.createDate'></DatePicker>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定</Button>
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>

    <Modal :mask-closable="false" :transfer=false v-model="itemModel" :width=750 title="在岗职业病人信息"
           @on-cancel="itemModel=false,detailItem={}">
      <Row>
        <Col span="24">
          <Form ref="itemForm" :class="'modal-form'" :show-message="false" :model="detailItem" :rules="itemRuleCustom"
                label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='姓名：' prop='name'>
                  <div v-if="mode === 'view'">{{ detailItem.name }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写姓名" type='text'
                         v-model='detailItem.name'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='性别：' prop='sex'>
                  <div v-if="mode === 'view'">{{ detailItem.sex }}</div>
                  <!--<Input v-else class='query-form-el' placeholder="请填写性别" type='text' v-model='detailItem.sex'></Input>-->
                  <Select v-else class='query-form-el' v-model='detailItem.sex'>
                    <Option value="男">男</Option>
                    <Option value="女">女</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='出生年月：' prop='birthDate'>
                  <div v-if="mode === 'view'">{{ renderViewDate(detailItem.birthDate) }}</div>
                  <DatePicker v-else class="query-form-el" placeholder="请选择出生年月"
                              v-model='detailItem.birthDate'></DatePicker>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='原工作岗位/工种：' prop='positionOld'>
                  <div v-if="mode === 'view'">{{ detailItem.positionOld }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写原工作岗位/工种" type='text'
                         v-model='detailItem.positionOld'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='现工作岗位/工种：' prop='positionNew'>
                  <div v-if="mode === 'view'">{{ detailItem.positionNew }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写现工作岗位/工种" type='text'
                         v-model='detailItem.positionNew'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='接触职业病危害因素年限：' prop='contactYears'>
                  <div v-if="mode === 'view'">{{ detailItem.contactYears }}</div>
                  <InputNumber v-else class='query-form-el' placeholder="请填写接触职业病危害因素年限" :min="0"
                               type='text' v-model='detailItem.contactYears'></InputNumber>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='疑似/确诊时间：' prop='confirmedTime'>
                  <div v-if="mode === 'view'">{{ renderViewDate(detailItem.confirmedTime) }}</div>
                  <DatePicker v-else class="query-form-el" placeholder="请选择疑似/确诊时间"
                              v-model='detailItem.confirmedTime'></DatePicker>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='诊断单位机构：' prop='diagnosticUnit'>
                  <div v-if="mode === 'view'">{{ detailItem.diagnosticUnit }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写诊断单位机构" type='text'
                         v-model='detailItem.diagnosticUnit'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='确诊职业病类型：' prop='occupationalDiseaseType'>
                  <div v-if="mode === 'view'">{{ detailItem.occupationalDiseaseType }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写确诊职业病类型" type='text'
                         v-model='detailItem.occupationalDiseaseType'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='职业病工伤鉴定等级：' prop='injuryLevel'>
                  <div v-if="mode === 'view'">{{ detailItem.injuryLevelName }}</div>
                  <!--<Input v-else class='query-form-el' placeholder="请填写职业病工伤鉴定等级" type='text' v-model='detailItem.injuryLevel'></Input>-->
                  <Select v-else class='' placeholder="请选择场所类别" v-model='detailItem.injuryLevel' label-in-value
                          @on-change='(value)=>{detailItem.injuryLevelName=value.label,detailItem.injuryLevel=value.value}'>
                    <Option v-for="item in dictMap.injuryLevelList" :value="item.codingCodeId" :label="item.codingName"
                            :key="item.codingCodeId">
                      <span>{{ item.codingName }}</span>
                      <!--<span style="float:right;color:#ccc">{{ item.note }}</span>-->
                    </Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='备注：' prop='remark'>
                  <div v-if="mode === 'view'">{{ detailItem.remark }}</div>
                  <Input v-else class='query-form-el' placeholder="请填写备注" type='textarea'
                         :autosize="{minRows:2,maxRows:5}" v-model='detailItem.remark'></Input>
                </FormItem>
              </Col>
            </Row>

          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="primary" class='ivu-btn-save' @click="itemSubmit('itemForm')">确定</Button>
        <Button type="primary" class='ivu-btn-cancel' @click="itemModel=false,detailItem={}">取消</Button>
        <!--<Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>-->
      </div>
    </Modal>


  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import {formatDate} from '@/tools/index'

var cascaderDom = () => import('@/components/cascader-dom.vue');
import pageCommonFunction from '@/components/pageCommonFunction.js'

export default {
  components: {cascaderDom},
  data() {
    return {
      ...this.createCommonDataField(),
      defaultLabel: sessionStorage('userId').getObject('userId').companyName,
      orgLists: [],
      userInfo: sessionStorage('userId').getObject('userId'),
      twoLevelOrgs: [],
      orgLoading: false,
      switchFlag: false,
      columns1: [
        {
          type: 'expand', width: 30,
          fixed: 'left',
          _disableExpand: true,
          render: (h, params) => {
            return h('Table', {
              props: {
                columns: [
                  {key: 'name', title: '姓名', align: 'center', minWidth: 80,},
                  {key: 'sex', title: '性别', align: 'center', minWidth: 80,},
                  {key: 'birthDate', title: '出生年月', align: 'center', minWidth: 100, render: this.renderCellDate},
                  {key: 'positionOld', title: '原工作岗位/工种', align: 'center', minWidth: 120,},
                  {key: 'positionNew', title: '现工作岗位/工种', align: 'center', minWidth: 120,},
                  {key: 'contactYears', title: '接触职业病危害因素年限', align: 'center', minWidth: 90,},
                  {
                    key: 'confirmedTime',
                    title: '疑似/确诊时间',
                    align: 'center',
                    minWidth: 100,
                    render: this.renderCellDate
                  },
                  {key: 'diagnosticUnit', title: '诊断单位机构', align: 'center', minWidth: 120,},
                  {key: 'occupationalDiseaseType', title: '确诊职业病类型', align: 'center', minWidth: 120,},
                  {key: 'injuryLevelName', title: '职业病工伤鉴定等级', align: 'center', minWidth: 120,},
                  // { key:'remark',title: '备注',  align: 'center', minWidth: 120, tooltip:true },
                ],//表头
                data: params.row.items,//内部表格展示的数据
              },
            })//我这里使用的是表格，大家也可以根据自己的实际情况更换别的组件
          }
        },
        {title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {key: 'companyName', title: '单位名称', align: 'center', minWidth: 120,},
        {key: 'subsidiaryCompany', title: '分管企业或分子公司', align: 'center', minWidth: 120,},
        {key: 'patientNumber', title: '在岗职业病人数', align: 'center', minWidth: 120,},
        this.getActionColumns()
      ],
      ruleCustom: {
        companyId: [{required: true, message: '请填写单位名称', trigger: 'change',}],
        subsidiaryCompany: [{required: true, message: '请填写分管企业或分子公司', trigger: 'change',}],
        patientNumber: [{required: true, message: '请填写在岗职业病人数', trigger: 'change', type: 'number'}],
      },
      tableHeight: 10,
      dictMap: {},
      detailItem: {},
      itemModel: false,
      itemAdd: false,
      columns2: [
        {title: '序号', width: 70, align: 'center', render: this.indexColumnsRender},
        {key: 'name', title: '姓名', align: 'center', minWidth: 80,},
        {key: 'sex', title: '性别', align: 'center', minWidth: 80,},
        {key: 'birthDate', title: '出生年月', align: 'center', minWidth: 100, render: this.renderCellDate},
        {key: 'positionOld', title: '原工作岗位/工种', align: 'center', minWidth: 120,},
        {key: 'positionNew', title: '现工作岗位/工种', align: 'center', minWidth: 120,},
        {key: 'contactYears', title: '接触职业病危害因素年限', align: 'center', minWidth: 120,},
        {key: 'confirmedTime', title: '疑似/确诊时间', align: 'center', minWidth: 100, render: this.renderCellDate},
        {key: 'diagnosticUnit', title: '诊断单位机构', align: 'center', minWidth: 120,},
        {key: 'occupationalDiseaseType', title: '确诊职业病类型', align: 'center', minWidth: 120,},
        {key: 'injuryLevelName', title: '职业病工伤鉴定等级', align: 'center', minWidth: 120,},
        {key: 'remark', title: '备注', align: 'center', minWidth: 120, tooltip: true},
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 110,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {type: 'primary', size: 'small'},
                style: {fontSize: '13px',},
                on: {
                  click: () => {
                    this.detailItem = {...params.row}
                    this.itemModel = true
                    this.itemAdd = false
                  }
                }
              }, '修改'),
              h('Divider', {props: {type: 'vertical'}}, ''),
              h('A', {
                props: {type: 'primary', size: 'small'},
                style: {fontSize: '13px', color: 'red'},
                on: {
                  click: () => {
                    this.dataToView.items.splice(params.index, 1)
                    this.dataToView.patientNumber = this.dataToView.items.length
                  }
                }
              }, '删除'),
            ])
          }
        }
      ],
      itemRuleCustom: {
        name: [{required: true, message: '请填写姓名', trigger: 'change',}],
        sex: [{required: true, message: '请填写性别', trigger: 'change',}],
        birthDate: [{required: true, message: '请填写出生年月', trigger: 'change', type: 'date'}],
        // positionOld: [ { required: true, message: '请填写原工作岗位/工种', trigger: 'change',}],
        positionNew: [{required: true, message: '请填写现工作岗位/工种', trigger: 'change',}],
        contactYears: [{required: true, message: '请填写接触职业病危害因素年限', trigger: 'change', type: 'number'}],
        confirmedTime: [{required: true, message: '请填写疑似/确诊时间', trigger: 'change', type: 'date'}],
        diagnosticUnit: [{required: true, message: '请填写诊断单位机构', trigger: 'change',}],
        occupationalDiseaseType: [{required: true, message: '请填写确诊职业病类型', trigger: 'change',}],
        injuryLevel: [{required: true, message: '请填写职业病工伤鉴定等级', trigger: 'change',}],
        // remark: [ { required: true, message: '请填写备注', trigger: 'change',}],
      },
      // api
      exportUrl: Api.exportOccupationalDiseaseStatistical,
      queryUrl: Api.queryOccupationalDiseaseStatistical,
      deleteUrl: Api.deleteOccupationalDiseaseStatistical,
      updateUrl: Api.updateOccupationalDiseaseStatistical,
      saveUrl: Api.saveOccupationalDiseaseStatistical,
      buttonLoading: false,

    }
  },
  computed: {
    itemColumn() {
      const columns = [...this.columns2];
      const columns1 = []
      columns.forEach(item => {
        if (this.mode !== 'view') {
          columns1.push(item)
        } else {
          if (item.key !== 'action') {
            columns1.push(item)
          }
        }
      })
      return columns1
    },
  },
  async mounted() {
    this.setTableHeight();
    await this.$http.get(Api.queryDictBycode + "env-00021", {}).then((res) => {
      this.dictMap = {
        'injuryLevelList': res.data.data['env-00021'],
      }
    }).catch(e => {
      this.$Message.error("数据字典获取失败")
    });
    this.queryTwoOrgInfo();
    this.query();
  },
  methods: {
    ...pageCommonFunction,
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 33;
      } else {
        this.tableHeight = this.tableHeight - 33;
      }
    },
    queryTwoOrgInfo() {
      if (sessionStorage('userId').getObject('userId').companyId != '18000000') {
        this.twoLevelOrgs.push({
          orgId: sessionStorage('userId').getObject('userId').twoLevelOrgId,
          orgName: sessionStorage('userId').getObject('userId').twoLevelOrgName
        });
      } else {
        this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
          this.twoLevelOrgs = res.data.data
        }).catch(e => {
        })
      }
    },
    remoteMethodSelectOrg(query) {
      if (query !== '') {
        this.orgLists = [];
        this.orgLoading = true;
        this.$http.get(Api.queryOrgList + "?companyId=" + this.userInfo.companyId + "&orgName=" + query + "&fromPage=1&pageSize=1000").then(res => {
          this.orgLists = res.data.data;
          this.orgLoading = false;
        }).catch(e => {
          this.orgLoading = false;
          this.$Message.error('请求失败');
        })
      } else {
        this.orgLoading = false;
      }
    },
    itemSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$Modal.confirm({
            title: '提示',
            content: '<p>是否要提交？</p>',
            onOk: () => {
              let _this = this
              _this.dataToView.items.splice()
              if (_this.itemAdd) {
                _this.dataToView.items.push(_this.detailItem)
              } else {
                _this.dataToView.items[_this.detailItem._index] = _this.detailItem
              }
              _this.dataToView.patientNumber = _this.dataToView.items.length
              // _this.dataToView.items.forEach(m=>{
              //     _this.dataToView.patientNumber +=1
              // })
              _this.itemModel = false
            },
            onCancel: () => {
            }
          })
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },

    deleteData(params) {
      this.deleteDateAjax(params);
    },
    exportList() {
      this.exportFormSubmit();
    },
    query() {

      this.queryAjax();
    },
    submit(name) {
      if (this.dataToView.items.length < 1) {
        this.$Message.warning('在岗职业病人信息至少填报一条');
      } else {
        this.submitAjax(name);
      }
    },
    createEmptyDataToAdd() {
      return {
        id: this.get_uuid(),
        patientNumber: 0,
        idFiles: [],
        items: [],
      }
    },
    async afterDataToViewInit() {
      // await this.getFiles1('id', 'examSelect');
    },

  }
}
</script>

<style lang='css' scoped>
@import '../../../index.css';
</style>
